package leetcode;

public class 两数之和链表 {
    static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {

        // 课程 A -》 链表 -> 基础篇
        ListNode dummy = new ListNode();
        ListNode curr = dummy;
        int carry = 0;
        while (l1 != null || l2 != null) {
            int x = l1 == null ? 0 : l1.val;
            int y = l2 == null ? 0 : l2.val;
            int total = x + y + carry;
            curr.next = new ListNode(total % 10);
            curr = curr.next;
            carry = total / 10;

            if (l1 != null) l1 = l1.next;
            if (l2 != null) l2 = l2.next;
        }
        if (carry != 0) curr.next = new ListNode(carry);
        return dummy.next;
    }
    public void display(ListNode node) {
        ListNode temp = node;
        while (temp.next!=null) {
            System.out.print(temp.next.val+" ");
            temp = temp.next;
        }
        System.out.println();
    }
    public void insert(ListNode target,int data) {
        ListNode temp = new ListNode();
        temp.val = data;
        ListNode p = target;
        while (p.next!=null) {
            p = p.next;
        }
        temp.next=null;
        p.next = temp;
    }
    public static void main(String[] args) {
        两数之和链表 test = new 两数之和链表();
        ListNode l1 = new ListNode();
        test.insert(l1,2);
        test.insert(l1,4);
        test.insert(l1,3);
        ListNode l2 = new ListNode();
//        for (int i = 0; i < 4; i++) {
//            test.insert(l2,9);
//        }
        test.insert(l2,5);
        test.insert(l2,6);
        test.insert(l2,4);
        test.display(l1);
        test.display(l2);
        ListNode listNode = test.addTwoNumbers(l1, l2);
        test.display(listNode);
    }
}
